package com.sharkpro.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.sharkpro.constants.RedisConstant;
import com.sharkpro.constants.SaltConstant;
import com.sharkpro.service.ImageService;
import com.sharkpro.utils.RedisUtil;
import com.sharkpro.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author jianxin.wei
 * @description
 * @date 2024/12/30 10:52
 */
@Service
public class ImageServiceImpl implements ImageService {
    @Resource
    RedisUtil redisUtil;
    @Override
    public ResultUtil getImage() {
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(200, 50);
        gifCaptcha.createCode();
        UUID uuid = UUID.randomUUID();
        String code = gifCaptcha.getCode();
        redisUtil.setMapCache(RedisConstant.RPKEY_IMAGE_CODE, SaltConstant.SALT + StrUtil.toString(uuid), code, 30, TimeUnit.MINUTES);
        JSONObject result = new JSONObject();
        result.set("imgCode",gifCaptcha.getCode());
        result.set("uuid",StrUtil.toString(uuid));
        result.set("img",gifCaptcha.getImageBase64());
        return new ResultUtil().success(result);
    }

    @Override
    public ResultUtil verifyImg(String uuid,String imgCode) {
        if (!redisUtil.containsMapKey(RedisConstant.RPKEY_IMAGE_CODE, SaltConstant.SALT + uuid)){
            return new ResultUtil().fail("图片验证码已过期，请重新生成验证码");
        }
        String code = String.valueOf(redisUtil.getMapCache(RedisConstant.RPKEY_IMAGE_CODE, SaltConstant.SALT + uuid));
        redisUtil.removeMapCache(RedisConstant.RPKEY_IMAGE_CODE, SaltConstant.SALT + uuid);
        if (!imgCode.equals(code)){
            return new ResultUtil().fail("图片验证码输入错误，请重试");
        }
        return new ResultUtil().success(true);
    }
}
